package com.liusy.taskengine;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.liusy.taskengine.resultmodel.ComparResult;
import com.liusy.taskengine.resultmodel.IResultModel;
import com.liusy.taskengine.taskexecute.AbstractTaskExecute;
import com.liusy.taskengine.taskexecute.ITaskExecute;
import com.liusy.taskengine.taskexecute.TaskExecute;



/**
 * 管理者(管理执行器)
 * 
 * @author liusy 2012-12-11
 */
public class TaskManager  {
	
	private static Logger log = Logger.getLogger(TaskExecute.class);
	 
	 private String taskManagerName = "我是管理者(管理执行器)......";
	 
	 //等待发布任务中的（执行器）
	 private Vector<ITaskExecute> obs;
	 
	 //当前存在的（执行器）
	 public int threadCount = 0;
	 
	 //是否开始执行
	 private int runFlag = TaskEngineConstant.OFF;

	 private IResultModel rm = null;

		public TaskManager(int runFlag,IResultModel rm) {
			this.rm = rm;
	    	this.runFlag=runFlag;
	    	obs = new Vector<ITaskExecute>();
	    	rm.start(this);
	    }
		
		public synchronized void addComparResults(ComparResult comparResult)
		{
			rm.addComparResults(comparResult);
		}
		
		/**
		 * 添加执行器
		 * @param o
		 */
	    public synchronized void addObserver(ITaskExecute o) {
	        if (o == null)
	            throw new NullPointerException();
			if (!obs.contains(o)) {
				((AbstractTaskExecute)o).setTaskManager(this);
			    obs.addElement(o);
			}
	    }
	    
	    /**
	     * 反回一个等待中的（执行器）
	     * @return
	     */
	    public  ITaskExecute getTaskExecute() {
	    	if(obs.size()>0)
	    	{
	    		ITaskExecute batchExecuteObserver= obs.get(0);
	    		obs.remove(0);
	    		return batchExecuteObserver;
	    	}
	    	return null;
	    }
	    
	    
	    /**
	     * 从等待中的（执行器）容器中移除
	     * @param o
	     */
	    public synchronized void deleteObserver(ITaskExecute o) {
	        obs.removeElement(o);
	    }

	    /**
	     * 通知执行器毁灭
	     */
	    public void notifyObservers() {
	    	notifyObservers(null);
	    	this.rm.interrupt();
	    }
	    /**
	     * 通知执行器毁灭
	     */
	    public void notifyObservers(Object arg) {
	        Object[] arrLocal = this.obs.toArray();
			synchronized (this) {
		        for (int i = arrLocal.length-1; i>=0; i--)
		            ((ITaskExecute)arrLocal[i]).ExecuteDestroy(this, arg);
		    }
	    }
	    
	    public synchronized void deleteObservers() {
	    	obs.removeAllElements();
	    }

	    public synchronized int countObservers() {
	    	return obs.size();
	    }
	    


	    public String getTaskManagerName() {
			return taskManagerName;
		}

		public void setTaskManagerName(String taskManagerName) {
			this.taskManagerName = taskManagerName;
		}

		public int getThreadCount() {
			return threadCount;
		}

		public void setThreadCount(int threadCount) {
			this.threadCount = threadCount;
		}

		public int getRunFlag() {
			return runFlag;
		}

		public void setRunFlag(int runFlag) {
			this.runFlag = runFlag;
		}

		public IResultModel getResultModel() {
			return rm;
		}

}
